import { defineStore } from "pinia";
import router from "@/router";
import { getUserInfo, login } from "@/api/auth";
import { storage } from "@/utils/storage";
import { useNavTabStore } from "./navTab";
import crypto from "@/utils/AESencryption";

interface IUserState {
  token: string | null;
  userInfo: {
    user: { [T: string]: string | number };
    roles: Array<string>;
  };
  permissions: string[];
}

export const useUserStore = defineStore({
  id: "user",
  state: (): IUserState =>
    <IUserState>{
      token: storage.get("token"),
      userInfo: storage.get("userInfo") || { user: {}, role: [] },
      permissions: [],
    },
  getters: {
    isLogin(state) {
      return Boolean(state.token);
    },
  },
  actions: {
    resetUser() {
      const navTabStore = useNavTabStore();
      storage.remove("userInfo");
      storage.remove("token");
      navTabStore.reset();
      this.$reset();
    },
    setToken(token: string) {
      this.token = token;
      storage.set("token", token);
    },
    async setUserInfo(userAccount: any, isRemember: boolean) {
      const {
        data: { permissions, roles, user },
      } = await getUserInfo();
      if (permissions && permissions.length) this.setPermissions(permissions);
      this.userInfo = { roles, user };
      storage.set("userInfo", this.userInfo);
      if (isRemember) {
        const data = crypto.encryptAES(userAccount);
        storage.set("userAccount", data);
      } else {
        storage.remove("userAccount");
      }
    },
    setPermissions(permissions: string[]) {
      this.permissions = permissions;
    },
    async login(params: any, isRemember: boolean) {
      const { data } = await login(params);
      this.setToken(data.token);
      router.push((router.currentRoute.value.query?.redirect || "/") as string);
      await this.setUserInfo(params, isRemember);
      ElNotification({
        title: "登录成功!",
        type: "success",
        message: `欢迎回来，${this.userInfo.username}`,
      });
    },
    logout() {
      ElMessageBox.confirm("您确定要退出登录吗？", "提示")
        .then(() => {
          this.resetUser();
          router.push("/login");
        })
        .catch(() => {});
    },
  },
});
